import { defineStore } from 'pinia';
import { getStorage, setStorage } from '@/utils/tools'
import { getUserDetail } from '@/api/user'

interface IUser {
    token: string | undefined;
    user: any;
    orderCount: any
}

export const userStore = defineStore({
    id: 'app-user',
    state: (): IUser => ({
        token: getStorage('token'),
        user: getStorage('user'),
        orderCount: {
            comment: 0,
            delivery: 0,
            payment: 0,
            received: 0,
            
        },
    }),
    actions: {
        async initUser() {
            const { data }: any = await getUserDetail()
            this.setUser(data.user);
            this.setOrderCount(data.order_count);
            return data.user
        },
        setUser(value: any) {
            setStorage('user', value);
            this.$patch({
                user: value
            })
        },
        setToken(value: any) {
            setStorage('token', value);
            this.$patch({
                token: value
            })
        },
        setOrderCount(value: any) {
            this.$patch({
                orderCount: value
            })
        },
    },
    getters: {
        getToken(state): any {
            return state.token
        },
        getUser(state): any {
            return state.user
        },
        getOrderCount(state): any {
            return state.orderCount
        },
    }
})


export default userStore;